package io.github.uicdb.badskill.network;

import com.google.common.collect.Lists;
import io.github.uicdb.badskill.PlayerSkillCapability;
import io.github.uicdb.badskill.PlayerSkillCapabilityProvider;
import io.github.uicdb.badskill.SkillOption;
import io.github.uicdb.badskill.SkillOptionManager;
import lombok.RequiredArgsConstructor;
import net.minecraft.client.Minecraft;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.entity.player.Player;
import net.minecraftforge.common.util.NonNullConsumer;
import net.minecraftforge.fml.LogicalSide;
import net.minecraftforge.network.NetworkEvent;
import net.minecraftforge.network.PacketDistributor;
import org.jetbrains.annotations.NotNull;

import java.util.Collection;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Supplier;

@RequiredArgsConstructor
public class PlayerLearnedSyncPackage {
    private final Collection<ResourceLocation> collection;
    public static PlayerLearnedSyncPackage create(Player player){
        return new PlayerLearnedSyncPackage(player.getCapability(PlayerSkillCapabilityProvider.CAPABILITY).resolve().orElseThrow().options.keySet());
    }
    public  void toBytes(FriendlyByteBuf buf) {
        buf.writeCollection(collection, FriendlyByteBuf::writeResourceLocation);
    }

    public static PlayerLearnedSyncPackage create(FriendlyByteBuf buf) {
        return new PlayerLearnedSyncPackage(buf.readCollection(Lists::newArrayListWithCapacity, FriendlyByteBuf::readResourceLocation));
    }

    public  void handle(Supplier<NetworkEvent.Context> contextSupplier) {
        var context=contextSupplier.get();
        context.enqueueWork(() -> {
            if(context.getDirection().getReceptionSide()==LogicalSide.CLIENT){
                Minecraft.getInstance()
                        .player.getCapability(PlayerSkillCapabilityProvider.CAPABILITY)
                        .ifPresent(capability -> {
                            capability.options.clear();
                            collection.forEach(resourceLocation -> {
                                SkillOption option = SkillOptionManager.INSTANCE.OPTIONS.get(resourceLocation);
                                if (option != null) {
                                    capability.options.put(resourceLocation, option);
                                }
                            });
                        });
            }
        });
        context.setPacketHandled(true);
    }
}
